<?php

namespace app\controllers;

use app\librarys\BaseController;
use app\librarys\Inteface;
use app\models\Manager;
use app\models\Order;
use app\models\Permission;
use yii\data\Pagination;
use app\models\Goods;
use app\models\User;
use app\models\Integral;
use app\models\Institution;
use yii\helpers\VarDumper;

/**
 * 订单管理
 * Class OrderController
 * @package app\controllers
 */
class OrderController extends BaseController
{
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * 展示系统所有的用户订单
     * @return string
     */
    public function actionUserOrderList()
    {
        $request = \Yii::$app->request;
        $current_console_user= Manager::getCurrentManager();
        $institutionCode = $current_console_user['institution_code'];
        $department=$current_console_user['department']['id'];

        //下拉选择的机构
        $institution = $institutionCode;
        if ($institutionCode == '0') {
            $institutionCode = $request->get('institution_code', '0');
        }

        //下拉列表相关数据
        $selectList = Institution::getInstitutionSelectList($institution, $institutionCode);

        $department_id = $request->get("department_id");
        if ($department_id == '') {
            $department_id = $department;
        }
        $pageSize = 10;

        $start_time = $request->get('start_time');
        $end_time = $request->get('end_time');
        $order_status = $request->get('order_status');
        $field = $request->get('field');
        $field_value = $request->get('field_value');

        if ($institutionCode == '0') {
            $totalCount = Order::getAllCount('', $start_time, $end_time, $order_status, $field, $field_value,'');
        } else {
            $totalCount = Order::getCountByInstitution($institutionCode, $start_time, $end_time, $order_status, $field, $field_value,$department_id);
        }

        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $totalCount,
        ]);

        if ($institutionCode == '0') {
            $items = Order::getAllList($pagination->offset, $pagination->limit, '', $start_time, $end_time, $order_status, $field, $field_value,'');
        } else {
            $items = Order::getListByInstitution($institutionCode, $pagination->offset, $pagination->limit, $start_time, $end_time, $order_status, $field, $field_value,$department_id);
        }

        return $this->render('user-order-list',
            [
                'start_time' => $start_time,
                'end_time' => $end_time,
                'order_status' => $order_status,
                'field' => $field,
                'field_value' => $field_value,
                'current_institution_code'=>$institutionCode,//$institution,
                //'selectedInstitution' => $selectList['selectedInstitution'],
                'institutionList'=>$selectList['institutionList'],
                'selectdepartment'=>$department_id,

                'items' => $items,
                'pagination' => $pagination
            ]);
    }

    /**
     * 流转订单列表(供机构查看本机构的所有流转订单)
     * @return string
     */
    public function actionFlowList()
    {
        $institutionCode = Manager::getCurrentManager()['institution_code'];
        if ($institutionCode == '0') {
            $institutionCode = \Yii::$app->request->get('institution_code');
        }

        $flowOrderStatus = \Yii::$app->request->get('flow_order_status', 0);

        $start_time = \Yii::$app->request->get('start_time');
        $end_time = \Yii::$app->request->get('end_time');
        $field = \Yii::$app->request->get('field');
        $field_value = \Yii::$app->request->get('field_value');

        $pageSize = 10;
        $totalCount = Order::getFlowCount($institutionCode, $flowOrderStatus, $start_time, $end_time, $field, $field_value);

        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $totalCount,
        ]);

        $items = Order::getFlowList($institutionCode, $flowOrderStatus, $pagination->offset, $pagination->limit, $start_time, $end_time, $field, $field_value);

        return $this->render('flow-list',
            ['items' => $items,
                'pagination' => $pagination,
                'current_institution_code' => $institutionCode,
                'flow_order_status' => $flowOrderStatus,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'field' => $field,
                'field_value' => $field_value
            ]);
    }

    /**
     * 订单详情
     * @return string
     */
    public function actionOrderDetailPartial()
    {
        $orderId = \Yii::$app->request->post('order_id');
        $item = Order::getDetail($orderId);

        $orderCode = \Yii::$app->request->post('order_code');
        $orderDeliveryItems = Order::getOrderDelivery($orderCode);

        //获取退货信息
        $backGoodsItems = Order::getBackGoodsRecord($orderCode);
        return $this->renderPartial('order-detail-partial',
            [
                'item' => $item,
                'order_delivery_items' => $orderDeliveryItems,
                'backGoodsItems' => $backGoodsItems
            ]
        );
    }

    /**
     * 获取物流信息
     * @return string
     */
    public function actionGetLogisticsHandler()
    {
        $logisticsCode = \Yii::$app->request->post('logistics_code');
        $items = Inteface::getLogistics($logisticsCode);
        return $this->renderJson($items);
    }

    /**
     * 流转订单详情
     * @return string
     */
    public function actionOrderFlowDetailPartial()
    {
        $orderFlowId = \Yii::$app->request->post('order_flow_id');
        $item = Order::getFlowDetail($orderFlowId);

        //退货信息
        $institution_code = '';
        if (!Permission::isSystemAdmin()) {
            $institution_code = $item['institution_code'];
        }

        $backGoodsItems = Order::getBackGoodsRecordForFlow($item['order_code'], $institution_code);

        return $this->renderPartial('order-flow-detail-partial',
            [
                'item' => $item,
                'backGoodsItems' => $backGoodsItems
            ]);
    }

    /**
     * 流转订单列表
     * @return string
     */
    public function actionOrderFlowListPartial()
    {
        $orderCode = \Yii::$app->request->post('order_code');
        $items = Order::getFlowListByOrderCode($orderCode);

        return $this->renderPartial('order-flow-list-partial', ['items' => $items]);
    }

    /**
     * 订单审核
     * @return string
     */
    public function actionApproveOrderFlowHandler()
    {
        $orderFlowId = \Yii::$app->request->post('order_flow_id');
        $orderCode = \Yii::$app->request->post('order_code');

        $status = Order::approveFlow($orderFlowId);
        if ($status == 10) {
            return $this->renderJson(null, 10, '订单状态不对。');
        } else {
            return $this->renderJson($orderCode);
        }
    }

    /**
     * 流转订单批量审核
     * @return string
     */
    public function actionBatchApproveOrderFlowHandler()
    {
        $orderFlowIdList = \Yii::$app->request->post('order_flow_id_list');
        if (isset($orderFlowIdList)) {
            foreach ($orderFlowIdList as $orderFlowId) {
                Order::approveFlow($orderFlowId);
            }
        }
        return $this->renderJson();
    }

    /**
     * 订单支付
     * @return string
     */
    public function actionPayOrderFlowHandler()
    {
        $orderFlowId = \Yii::$app->request->post('order_flow_id');
        $orderCode = \Yii::$app->request->post('order_code');

        $status = Order::payFlow($orderFlowId);  //0:成功; 1:失败(系统错误) 10:订单状态不对,不能进行支付; 110:订单处理为"待审核订单"; 112:订单处理为“未结算订单”
        switch ($status) {
            case 1:
                return $this->renderJson(null, 1, '系统错误');
                break;
            case 10:
                return $this->renderJson(null, 10, '订单状态不对。');
                break;
            case 110:
                return $this->renderJson(null, 110, '此订单需要审核。');
                break;
            case 112:
                return $this->renderJson(null, 112, '机构账户可用额不足。');
                break;
            default:
                return $this->renderJson($orderCode);
                break;
        }
    }

    /**
     *  添加流转订单
     * @return string
     */
    public function actionAddOrderFlowHandler()
    {
        $orderFlowId = \Yii::$app->request->post('order_flow_id');
        $orderCode = \Yii::$app->request->post('order_code');

        $status = Order::addInstitutionFlow($orderCode);  // 0:成功; 1:失败(系统错误); 10:此流转订单已到系统，无需再流转了; 20:未找到需要流转的订单
        switch ($status) {
            case 1:
                return $this->renderJson(null, 1, '系统错误');
                break;
            case 10:
                return $this->renderJson(null, 10, '此流转订单已到系统。');
                break;
            case 110:
                return $this->renderJson(null, 20, '未找到需要流转的订单。');
                break;
            default:
                return $this->renderJson($orderCode);
                break;
        }
    }

    /**
     * 取消用户订单
     */
    public function actionCancelOrderHandler()
    {
        $orderCode = \Yii::$app->request->post('order_code');
        $status = Order::cancelOrder($orderCode, '');
        return $this->renderJson(null, $status, '');
    }

    /**
     * 导入订单
     * @return string
     */
    public function actionOrderImportPartial()
    {
        $institutionCode = Manager::getCurrentManager()['institution_code'];
        $institutionList = Institution::getAllEnabledListWithHierarchy($institutionCode);
        return $this->renderPartial('order-import-partial', ['current_institution_code' => $institutionCode, 'institutionList' => $institutionList]);
    }

    /**
     * 导入订单Excel数据获取
     * @return string
     * @throws \Exception
     * @throws \PHPExcel_Exception
     * @throws \yii\db\Exception
     */
    public function actionImportOrderHandler()
    {
        /*//当前操作人员id----------------
        $current_console_user = Manager::getCurrentManager();
        $operator_id = $current_console_user['id'];
        //------------------------------*/

        $request = \Yii::$app->request;

        $institutionCode = $request->get("institutionCode");
        //$isSendIntegral = $request->get("isSendIntegral");
        $flag = 0;
        //$reason = "导入订单发放积分";
        $amount = 0;
        $iCount = 0;
        $msg = '';
        $right_data = array();
        $error_data = array();

        //检查excel正确性
        $file = $_FILES['file']['name'];
        if ($_POST) {
            if (empty($file)) {
                $flag = 2;
                $msg = json_encode("请选择要上传的文件!");
            } else {
                $file_info = pathinfo($file);
                $file_ext = $file_info['extension'];
                if (!in_array($file_ext, array('xls', 'xlsx'))) {
                    $flag = 2;
                    $msg = json_encode("文件类型不正确，仅支持xls,xlsx类型的文件！");
                } else {
                    $objPHPExcel = \PHPExcel_IOFactory::load($_FILES['file']['tmp_name']);

                    $sheet = $objPHPExcel->getSheet(0);
                    $highestRow = $sheet->getHighestRow();           //取得总行数
                    $highestColumn = $sheet->getHighestColumn(); //取得总列

                    if ($highestRow > 5002) {
                        $flag = 2;
                        $msg = json_encode("一次导入数据不能超过5000条记录！");
                    } else {
                        //检查文件内容的正确性
                        for ($j = 2; $j <= $highestRow; $j++)                        //从第二行开始读取数据
                        {
                            $is_error = 0;
                            $v = array();
                            $v['error'] = "";

                            for ($k = 'A'; $k <= 'M'; $k++)            //从A列读取数据
                            {
                                $value = $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();//读取单元格

                                //获取数据
                                switch ($k) {
                                    case 'A':
                                        $v['goodCode'] = trim($value);
                                        break;
                                    case 'B':
                                        $v['num'] = trim($value);
                                        break;
                                    case 'C':
                                        $v['name'] = trim($value);
                                        break;
                                    case 'D':
                                        $v['province'] = trim($value);
                                        break;
                                    case 'E':
                                        $v['city'] = trim($value);
                                        break;
                                    case 'F':
                                        $v['region'] = trim($value);
                                        break;
                                    case 'G':
                                        $v['address'] = trim($value);
                                        break;
                                    case 'H':
                                        $v['phone'] = trim($value);
                                        break;
                                    case 'I':
                                        $v['email'] = trim($value);
                                        break;
                                    case 'J':
                                        $v['postCodes'] = trim($value);
                                        break;
                                    case 'K':
                                        $v['orderRemark'] = trim($value);
                                        break;
                                    case 'L':
                                        $v['idcardName'] = trim($value);
                                        break;
                                    case 'M':
                                        $v['idcardNumber'] = trim($value);
                                        break;
                                }


                            }

                            $goodCode = Goods::getGoodsDetail($institutionCode, $v['goodCode']);
                            //产品编码不正确
                            if ($goodCode == "" || $goodCode == null) {
                                $v['error'] .= '未在该机构找到该产品！';
                                $is_error = 1;
                                $flag = 1;
                            } else {
                                $v['integral'] = $goodCode['selling_integral'];
                                $v['selling_price'] = $goodCode['selling_price'];
                                // $v['supply_price'] = $goodCode[0]['supply_price'];
                                $v['goodName'] = $goodCode['name'];
                            }

                            //数量检查
                            if (!($v['num'] != "" && is_numeric($v['num']))) {
                                $v['error'] .= '数量不为数字！';
                                $is_error = 1;
                                $flag = 1;
                            }

                            //其它非空项目检查
                            if ($v['name'] == "" || $v['province'] == "" || $v['city'] == "" || $v['address'] == "" || $v['phone'] == "") {
                                $v['error'] .= '检查必填项是否填写完整！';
                                $is_error = 1;
                                $flag = 1;
                            }
                            //正确的数据 装入到正确记录数组
                            //错误的数据 装入到错误记录数组
                            if ($is_error) {
                                $error_data[] = $v;

                            } else {
                                $right_data[] = $v;
                                $iCount = $iCount + 1;
                                $amount += $v['selling_price'] * $v['num'];
                            }
                        }
                        $msg = json_encode($error_data);
                    }
                }
            }
        }


        //检验是否发积分
        /*if ($flag == 0) {

            $transaction = \Yii::$app->db->beginTransaction();
            try {
                //发积分则生成发分记录
                if ($isSendIntegral == 1) {
                    $send_record_id = Integral::saveInstitutionWalfare($institutionCode, $operator_id, $reason);
                    if ($send_record_id == null || $send_record_id == '') {
                        throw new \Exception('写入机构福利失败！');
                    }
                }
                foreach ($right_data as $record) {

                    $data = [];
                    $goods = [];
                    $data['institution_code'] = $institutionCode;
                    $data['total_price'] = $record['selling_price'] * $record['num'];
                    $data['receiver']['name'] = $record['name'];
                    $data['receiver']['phone'] = $record['phone'];
                    $data['receiver']['province'] = $record['province'];
                    $data['receiver']['city'] = $record['city'];
                    $data['receiver']['region'] = $record['region'];
                    $data['receiver']['address'] = $record['address'];
                    $data['receiver']['remark'] = '';
                    $data['remark'] = $record['orderRemark'];
                    $goods['code'] = $record['goodCode'];
                    $goods['name'] = $record['goodName'];
                    $goods['price'] = $record['selling_price'];
                    $goods['quantity'] = $record['num'];
                    $data['goods_list'][0] = $goods;
                    $data['isPay'] = 1;

                    //检查是否发积分,=1表示要发分
                    if ($isSendIntegral == 1) {
                        //检查添加用户并发积分
                        $record['id'] = 0;
                        $record['code'] = 0;
                        $record['institution_code'] = $institutionCode;
                        $record['remark'] = '';
                        $record['isEnabled'] = 1;
                        $result = User::addUser($record);
                        if ($result['userId'] == '0') {
                            throw new \Exception('新增用户[' . ['name'] . ']失败！');
                        } else {
                            $record['userId'] = $result['userId'];
                        }
                        $result = Integral::saveUserIntegral($institutionCode, $send_record_id, $result['userId'], $record['integral'] * $record['num'], $reason);
                        if ($result) {
                            throw new \Exception('用户[' . $record['name'] . ']发放积分失败！');
                        }

                        //生成用户订单
                        $data['user_id'] = $record['userId'];

                    } else {
                        //生成用户订单  新写存储过程
                        $data['isPay'] = 0;
                    }

                    $orderId = Order::addWithImport($data);

                    if ($orderId == null) {
                        throw new \Exception('用户[' . $record['name'] . ']生成订单失败！');
                    }
                    //生成流转订单
                }

                $transaction->commit();
            } catch (\Exception $e) {
                $transaction->rollBack();
                throw $e;

            }
        }*/

        return $this->renderJson(['iCount' => $iCount, 'amount' => $amount, 'right_data' => $right_data], $flag, $msg);
    }

    /**
     * 确认导入订单
     * @return string
     * @throws \Exception
     * @throws \yii\db\Exception
     */
    public function actionImportOrderConfirmHandler()
    {
        //当前操作人员id----------------
        $current_console_user = Manager::getCurrentManager();
        $operator_id = $current_console_user['id'];
        //------------------------------

        $request = \Yii::$app->request;
        $institutionCode = $request->post("institutionCode");
        //$isSendIntegral = $request->post("isSendIntegral");
        $importType = $request->post("importType");
        $right_data = $request->post('orderList');

        $walfare_type = 1;
        $reason = "导入订单发放积分";
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            //发积分则生成发分记录
            if ($importType == 3) {
                $send_record_id = Integral::saveInstitutionWalfare($institutionCode, $operator_id, $reason, $walfare_type);
                if ($send_record_id == null || $send_record_id == '') {
                    throw new \Exception('写入机构福利失败！');
                }
            }
            foreach ($right_data as $record) {

                $data = [];
                $goods = [];
                $data['institution_code'] = $institutionCode;
                $data['total_price'] = $record['selling_price'] * $record['num'];
                $data['receiver']['name'] = $record['name'];
                $data['receiver']['phone'] = $record['phone'];
                $data['receiver']['province'] = $record['province'];
                $data['receiver']['city'] = $record['city'];
                $data['receiver']['region'] = $record['region'];
                $data['receiver']['address'] = $record['address'];
                $data['receiver']['remark'] = '';
                $data['remark'] = $record['orderRemark'];
                $goods['code'] = $record['goodCode'];
                $goods['name'] = $record['goodName'];
                $goods['price'] = $record['selling_price'];
                $goods['quantity'] = $record['num'];
                $data['goods_list'][0] = $goods;
                $data['isPay'] = 1;
                $data['idcardName'] = $record['idcardName'];
                $data['idcardNumber'] = $record['idcardNumber'];

                //非仅生成用订单（0）方式都需要添加用户
                if ($importType > 1) {
                    //检查添加用户并发积分
                    $record['id'] = 0;
                    $record['code'] = 0;
                    $record['institution_code'] = $institutionCode;
                    $record['remark'] = '';
                    $record['isEnabled'] = 1;
                    $record['wx_openid'] = '';
                    $record['header_url'] = '';
                    $result = User::addUser($record);
                    if ($result['userId'] == '0') {
                        throw new \Exception('新增用户[' . ['name'] . ']失败！');
                    } else {
                        $record['userId'] = $result['userId'];
                    }

                    //检查是否发积分,=1表示要发分
                    if ($importType == 3) {
                        $result = Integral::saveUserIntegral($institutionCode, $send_record_id, $result['userId'], $record['integral'] * $record['num'], $reason);
                        if ($result) {
                            throw new \Exception('用户[' . $record['name'] . ']发放积分失败！');
                        }
                    }

                    //生成用户订单
                    $data['user_id'] = $record['userId'];

                } else {
                    //生成用户订单  新写存储过程
                    $data['isPay'] = 0;
                }

                $orderId = Order::addWithImport($data);

                if ($orderId == null) {
                    throw new \Exception('用户[' . $record['name'] . ']生成订单失败！');
                }
                //生成流转订单
            }

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;

        }

        return $this->renderJson(0, 0, 0);
    }
}